<script>
import * as echarts from 'echarts'

export default {
  name: 'DeviceChart',
  props: {
    formData: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      currentChart: null,
      option: {
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: [],
            type: 'line'
          }
        ]
      }
    }
  },
  watch: {
    formData: {
      handler(e) {
        this.changeChartOption(e)
      }
    }
  },
  mounted() {
    this.initChart()
    setTimeout(() => {
      this.changeChartOption(this.formData)
    }, 1000)
  },
  methods: {
    initChart() {
      this.$nextTick(() => {
        const dom = document.querySelector('#chart')
        this.currentChart = echarts.init(dom)
        this.currentChart.setOption(this.option)
      })
    },
    changeChartOption(e) {
      const xAxisData = []
      const seriesData = []
      for (const item of e) {
        xAxisData.push(item['key'])
        seriesData.push(item['value'])
      }
      this.option.xAxis.data = xAxisData
      this.option.series[0].data = seriesData
      this.currentChart.setOption(this.option)
    }
  }
}
</script>

<template>
  <div class='com-device-chart-container'>
    <div id='chart' class='chart' />
  </div>
</template>

<style>
.com-device-chart-container {
  height: 100%;
  width: 100%;

  .chart {
    height: 100%;
  }
}
</style>
